const router = require('koa-router')()
const user = require('../bin/user')
const project = require('../bin/project')

router.get('/', async (ctx, next) => {
  ctx.render('index', {
    title: 'Hello Koa 2!'
  })
})

router.get('/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
})

router.get('/graph', async (ctx, next) => {
  let x = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
  let y = [820, 932, 901, 934, 1290, 1330, 820];
  let dt = x.map((d, i) => ({name: d, value: y[i]}));
  ctx.success(dt);
})

router.get('/login', async (ctx, next) => {
  let username = ctx.query.user;
  let password = ctx.query.password;
  await user.login(username, password).then((rst) => {
    ctx.success(rst);
  }, (rst) => {
    ctx.error(1, rst);
  });
})

router.post('/saveProject', async (ctx, next) => {
  let query = ctx.request.body;
  let username = query.username;
  let pId = query.id || '';
  let pData = query.data;
  console.log([username, pId]);
  await project.save(username, pId, pData).then((rst) => {
    ctx.success(rst);
  }, (rst) => {
    ctx.error(1, rst);
  });
})

router.get('/getProjrctInfo', async (ctx, next) => {
  let pId = ctx.query.projectId;
  await project.getProjrct(pId).then((rst) => {
    ctx.success(rst);
  }, (rst) => {
    ctx.error(1, rst);
  });
})

router.get('/getProjectList', async (ctx, next) => {
  let username = ctx.query.username;
  await project.getList(username).then((rst) => {
    ctx.success(rst);
  }, (rst) => {
    ctx.error(1, rst);
  });
})

// http://localhost:3000/update?username=test1&projectId=5b6d6001e7ebe6821ca835f7&data={}
// http://localhost:3000/save?username=test1&projectName=&data=001

module.exports = router
